package com.gdssoft.pdaweb.service.ws.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.jws.WebParam;
import javax.jws.WebService;


import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gdssoft.core.command.QueryFilter;
import com.gdssoft.core.dao.impl.BaseDaoImpl;
import com.gdssoft.core.service.impl.BaseServiceImpl;
import com.gdssoft.core.util.AppUtil;
import com.gdssoft.core.util.DateUtil;
import com.gdssoft.core.util.StringUtil;
import com.gdssoft.framework.dao.system.AppUserDao;
import com.gdssoft.framework.model.system.AppRole;
import com.gdssoft.framework.model.system.AppUser;
import com.gdssoft.pdaweb.dao.CheckTaskDao;
import com.gdssoft.pdaweb.dao.CheckWorkOrderDao;
import com.gdssoft.pdaweb.dao.CrmWorkOrderDao;
import com.gdssoft.pdaweb.dao.PdaMaterialDetailDao;
import com.gdssoft.pdaweb.dao.PdaMaterialHeadDao;
import com.gdssoft.pdaweb.dao.PdaMdAssetDetailDao;
import com.gdssoft.pdaweb.dao.PdaMdAssetInfoDao;
import com.gdssoft.pdaweb.dao.RepairWorkOrderDao;
import com.gdssoft.pdaweb.dao.PdaApplyRepairDao;
import com.gdssoft.pdaweb.dao.am.AmMonthPlanDao;
import com.gdssoft.pdaweb.dao.am.AmMonthPlanReadDao;
import com.gdssoft.pdaweb.dao.am.PdaAmMeterDao;
import com.gdssoft.pdaweb.dao.am.PdaAmMeterListDao;
import com.gdssoft.pdaweb.dao.water.PdaWaterListDao;
import com.gdssoft.pdaweb.dao.water.PdaWaterMeterDao;
import com.gdssoft.pdaweb.dao.water.WaterMeterMonthPlanDao;
import com.gdssoft.pdaweb.dao.water.WaterMeterMonthPlanReadDao;

import com.gdssoft.pdaweb.model.CheckTask;
import com.gdssoft.pdaweb.model.CheckWorkOrder;
import com.gdssoft.pdaweb.model.CrmWorkOrder;
import com.gdssoft.pdaweb.model.PdaLog;
import com.gdssoft.pdaweb.model.PdaMaterialDetail;
import com.gdssoft.pdaweb.model.PdaMaterialHead;
import com.gdssoft.pdaweb.model.PdaMdAssetDetail;
import com.gdssoft.pdaweb.model.PdaMdAssetInfo;
import com.gdssoft.pdaweb.model.RepairWorkOrder;
import com.gdssoft.pdaweb.model.am.AmMonthPlan;
import com.gdssoft.pdaweb.model.am.AmMonthPlanRead;
import com.gdssoft.pdaweb.model.am.PdaAmMeter;
import com.gdssoft.pdaweb.model.am.PdaAmMeterList;
import com.gdssoft.pdaweb.model.PdaApplyRepair;
import com.gdssoft.pdaweb.model.water.PdaWaterList;
import com.gdssoft.pdaweb.model.water.PdaWaterMeter;
import com.gdssoft.pdaweb.model.water.WaterMeterMonthPlan;
import com.gdssoft.pdaweb.model.water.WaterMeterMonthPlanRead;
import com.gdssoft.pdaweb.service.deviceReg.DeviceRegService;
import com.gdssoft.pdaweb.service.ws.PdaService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import com.gdssoft.pdaweb.service.EamService;
import com.gdssoft.pdaweb.service.PdaLogService;

@WebService(endpointInterface = "com.gdssoft.pdaweb.service.ws.PdaService", 
		serviceName="PdaService", targetNamespace="http://gdssoft.foxconn.com/")
public class PdaServiceImpl implements PdaService {
	private AppUserDao appUserDao;
	private CrmWorkOrderDao crmWorkOrderDao;
	private CheckWorkOrderDao checkWorkOrderDao;
	private CheckTaskDao checkTaskDao;
	private RepairWorkOrderDao repairWorkOrderDao;
	private WaterMeterMonthPlanReadDao waterMeterMonthPlanReadDao;
	private AmMonthPlanReadDao amMonthPlanReadDao;
	private PdaMdAssetInfoDao pdaMdAssetInfoDao;
	private PdaMdAssetDetailDao pdaMdAssetDetailDao;
	private DeviceRegService deviceRegService;
	private PdaMaterialHeadDao pdaMaterialHeadDao;
	private PdaMaterialDetailDao pdaMaterialDetailDao;
	private PdaApplyRepairDao  pdaApplyRepairDao;
	private PdaWaterListDao pdaWaterListDao;
	private PdaAmMeterListDao pdaAmMeterListDao;
	private PdaWaterMeterDao pdaWaterMeterDao;
	private PdaAmMeterDao pdaAmMeterDao;
	private EamService eamService;
	private WaterMeterMonthPlanDao waterMeterMonthPlanDao;
	private AmMonthPlanDao amMonthPlanDao;
	private PdaLogService pdaLogService;
	private transient final Log logger = LogFactory.getLog(getClass());
	
	
	public PdaServiceImpl(
			AppUserDao appUserDao, 
			CrmWorkOrderDao crmWorkOrderDao,
			CheckWorkOrderDao checkWorkOrderDao,
			CheckTaskDao checkTaskDao,
			RepairWorkOrderDao repairWorkOrderDao,
			WaterMeterMonthPlanReadDao waterMeterMonthPlanReadDao,
			AmMonthPlanReadDao amMonthPlanReadDao,
			PdaMdAssetInfoDao pdaMdAssetInfoDao,
			PdaMdAssetDetailDao pdaMdAssetDetailDao,
			DeviceRegService deviceRegService,
			PdaMaterialHeadDao pdaMaterialHeadDao,
			PdaMaterialDetailDao pdaMaterialDetailDao,
			PdaApplyRepairDao  pdaApplyRepairDao,
			PdaWaterListDao pdaWaterListDao,
			PdaAmMeterListDao pdaAmMeterListDao,
			PdaWaterMeterDao pdaWaterMeterDao,
			PdaAmMeterDao pdaAmMeterDao,
			EamService eamService,
			WaterMeterMonthPlanDao waterMeterMonthPlanDao,
			AmMonthPlanDao amMonthPlanDao,
			PdaLogService pdaLogService
			) 
	{
		this.appUserDao = appUserDao;
		this.crmWorkOrderDao = crmWorkOrderDao;
		this.checkWorkOrderDao = checkWorkOrderDao;
		this.checkTaskDao = checkTaskDao;
		this.repairWorkOrderDao = repairWorkOrderDao;
		this.waterMeterMonthPlanReadDao = waterMeterMonthPlanReadDao;
		this.amMonthPlanReadDao = amMonthPlanReadDao;
		this.pdaMdAssetInfoDao = pdaMdAssetInfoDao;
		this.pdaMdAssetDetailDao = pdaMdAssetDetailDao;
		this.deviceRegService = deviceRegService;
		this.pdaMaterialHeadDao = pdaMaterialHeadDao;
		this.pdaMaterialDetailDao = pdaMaterialDetailDao;
		this.pdaApplyRepairDao = pdaApplyRepairDao;

		this.pdaWaterListDao =pdaWaterListDao;
		this.pdaAmMeterListDao=pdaAmMeterListDao;
		
		this.pdaWaterMeterDao =pdaWaterMeterDao;
		this.pdaAmMeterDao = pdaAmMeterDao;
		
		this.eamService = eamService;
		
		this.waterMeterMonthPlanDao = waterMeterMonthPlanDao;
		this.amMonthPlanDao = amMonthPlanDao;
		this.pdaLogService = pdaLogService;
	}
	
	@Override
	public  long  verifyAuth(String username, String password, String macAddress) {
		String actionStr ;
		String userInfo ="【登录信息】用户："+username+"，设备编号："+macAddress+".";
		long result = 0;
		//用户名不为空
		if(!"".equals(username) && username!=null){
			AppUser appUser = appUserDao.findByUserName(username);
			//账号是否存在
			if (appUser != null) {
				//密码不能为空
				if(StringUtils.isNotEmpty(password)){
					String newPassword = StringUtil.encryptSha256(password);
					//密码比对
					if(appUser.getPassword().equalsIgnoreCase(newPassword)){
						//用户不被禁用
						if(appUser.getStatus()==1){
							//设备是否注册
							if(deviceRegService.checkActivity(macAddress)){
								actionStr = "pda用户登入系统成功."+userInfo;
								this.loginLog(username, actionStr);
							    return result = 4;//所有验证均已通过
							
							}
							else{
								actionStr = "pda用户登入系统失败."+userInfo+"【失败原因】设备未注册.";
								this.loginLog(username, actionStr);
								return result = 5;//设备未注册
							}
							//result = 4;
						}
						else{
							actionStr = "pda用户登入系统失败."+userInfo+"【失败原因】用户禁用.";
							this.loginLog(username, actionStr);
							result = 3;//用户禁用
						}
					}
					else{
						actionStr = "pda用户登入系统失败."+userInfo+"【失败原因】用户密码错误.";
						this.loginLog(username, actionStr);
						result = 2;//表示密码错误
					}
				}
			}
			else {
				actionStr = "pda用户登入系统失败."+userInfo+"【失败原因】用户账号不存在";
				this.loginLog(username, actionStr);
				result =1;//表示账号不存在
				}
		}
		return result;
		//return false;
	}
	
	public void loginLog(String username,String strAction ){
		PdaLog pdaLog = new PdaLog();
 		//String nowDate = DateUtil.dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
		Date nowDate = Calendar.getInstance().getTime();
		pdaLog.setOperateTime(nowDate);
		pdaLog.setCreatedDt(nowDate);
		pdaLog.setCreatedBy("PdaService");
		pdaLog.setUserId(username);
		pdaLog.setLogType((short) 2);
		pdaLog.setAction(strAction);
		try{
		    pdaLogService.save(pdaLog);
		}
		catch(Exception ex){
			logger.info(strAction+"日志记录到数据库失败 " );
		}
	}
	
/*
 * (non-Javadoc)
 * @see com.gdssoft.pdaweb.service.ws.PdaService#modifyPassword(java.lang.String, java.lang.String, java.lang.String)
 */
	@Override
	public boolean modifyPassword(String username, String oldPassword,
			String newPassword) {
		if(!"".equals(username) && username!=null){
			AppUser appUser = appUserDao.findByUserName(username);
			//账号是否存在
			if (appUser != null) {
				if(StringUtils.isNotEmpty(oldPassword)&& StringUtils.isNotEmpty(newPassword)){
					String Password = StringUtil.encryptSha256(oldPassword);
					String passwordNew =StringUtil.encryptSha256(newPassword);
					//密码比对
					if(appUser.getPassword().equalsIgnoreCase(Password)){
						//用户不被禁用
						if(appUser.getStatus()==1){
							appUser.setPassword(passwordNew);
							appUserDao.saveOrUpdate(appUser);
							return true;
						}
						
						}
				}	
				}
			}
		return false;
	}

	@Override
	public String getAppVersion() {
		return AppUtil.getRealTimeConfigValue("pda.app.version");
	}
	
	@Override
	public String listWorkOrder(String dutyPerson) {
		//记日志
		logger.info("request args : " + dutyPerson);
		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}

		String hql = "from CrmWorkOrder cwo where cwo.dutyPerson=? and cwo.workStatus=1";
		List<CrmWorkOrder> list = this.crmWorkOrderDao.findByHql(hql, 
				new String[]{dutyPerson});

		if (list.size() > 0) {
			//更新下载数据的时间
			for (CrmWorkOrder cwo : list) {
				cwo.setDownLoadDt(DateUtil.dateFormat(new Date()));
				cwo.setUpdatePerson(dutyPerson);
				cwo.setUpdateDt(new Date());
				crmWorkOrderDao.saveOrUpdate(cwo);
			}
			return toJsonResult(list);
		}
		else
			return toJsonResult("没有数据");
	}
	@Override
	public String queryWorkOrder(String activityUID, String workStatus, 
			String contactsPerson, String contactsPhone, String description,
			String completionDateFrom, String completionDateTo,
			String dutyPerson) {
		//记日志
		logger.info("request args : " + activityUID + ", " + contactsPerson + 
				", " + contactsPhone + ", " + description + 
				", " + completionDateFrom + ", " + completionDateTo + ", " + dutyPerson);
		
		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}
		
		//List<CrmWorkOrder> list = crmWorkOrderDao.listByDutyPerson(dutyPerson);
		List<String> args = new ArrayList<String>();
		String hql = "from CrmWorkOrder cwo where cwo.dutyPerson=?";
		args.add(dutyPerson);

		if (!"".equals(completionDateFrom) || !"".equals(completionDateTo)) {
			if ("".equals(completionDateFrom)) 
				completionDateFrom = "1900/01/01 00:00:00";
			if ("".equals(completionDateTo)) 
				completionDateTo = "2999/01/01 00:00:00";
			
			hql += " and cwo.plannedCompletion>=to_date(?,'YYYY-MM-DD HH24:MI:SS') " +
					" and cwo.plannedCompletion<=to_date(?,'YYYY-MM-DD HH24:MI:SS') ";
			
			args.add(completionDateFrom);
			args.add(completionDateTo);
		}

		if (!"".equals(activityUID)) {
			hql += " and cwo.activityUID like ?";
			args.add("%" + activityUID + "%");
		}
		if (!"".equals(contactsPerson)) {
			hql += " and cwo.contactPerson like ?";
			args.add("%" + contactsPerson + "%");
		}
		if (!"".equals(contactsPhone)) {
			hql += " and cwo.contactPhoneNo like ?";
			args.add("%" + contactsPhone + "%");
		}
		if (!"".equals(description)) {
			hql += " and cwo.workDescription like ?";
			args.add("%" + description + "%");
		}
		if (!"".equals(workStatus)) {
			hql += " and cwo.workStatus=?";
			args.add(workStatus);
		}
		
		List<CrmWorkOrder> list = this.crmWorkOrderDao.findByHql(hql, args.toArray());
		
		if (list.size() > 0) 
			return toJsonResult(list);
		else
			return toJsonResult("没有数据");
	}
	
	@Override
	public boolean updateWorkOrder(String activityUID, String workStatus,
			String plannedCompletion, String comment, String updatePerson) {
		
		logger.info("request args : " + activityUID + ", " + workStatus + ", " 
				+ plannedCompletion + ", " + comment + ", " + updatePerson);
		
		CrmWorkOrder cwo = crmWorkOrderDao.getByActivityUID(activityUID);
		
		if (plannedCompletion == "" || "".equals(plannedCompletion)) {
			//完成时间为空，代表PDA上并未处理该记录，将PDA下载时间置空，下次还可以下载进行处理
			cwo.setDownLoadDt("");
		} else {
			//更新状态、处理时间、备注和PDA上传时间
			cwo.setWorkStatus(workStatus);
			cwo.setPlannedCompletion(DateUtil.dateParse(plannedCompletion));
			cwo.setComment(comment);
			cwo.setUpdatePerson(updatePerson);
			cwo.setUpdateDt(new Date());
			cwo.setUploadDt(DateUtil.dateFormat(new Date()));
		}
		
		crmWorkOrderDao.saveOrUpdate(cwo);
		
		CrmWorkOrder newObj = crmWorkOrderDao.getByActivityUID(activityUID);
		
		return (newObj.getActivityUID()==cwo.getActivityUID() 
				&& newObj.getWorkStatus()==cwo.getWorkStatus());
		
	}

	@Override
	public String listCheckWorkOrder(String dutyPerson) {

		logger.info("request args : " + dutyPerson);
		
		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}
		
		String hql = "from CheckWorkOrder cwo where cwo.appointPeople=? and cwo.status='1'";
		
		List<CheckWorkOrder> list = this.checkWorkOrderDao.findByHql(hql, 
				new String[]{dutyPerson});

		if (list.size() > 0) {
			//更新下载数据的时间
			for (CheckWorkOrder cwo : list) {
				cwo.setDownLoadDt(DateUtil.dateFormat(new Date()));
				cwo.setUpdatePerson(dutyPerson);
				cwo.setUpdateDt(new Date());
				checkWorkOrderDao.saveOrUpdate(cwo);
			}
			return toJsonResult(list);
		}
		else
			return toJsonResult("没有数据");
	}
	@Override
	public String queryCheckWorkOrder(String workStatus,
			String completionDateFrom, String completionDateTo, String dutyPerson) {
		
		logger.info("request args : " + workStatus + ", " 
				+ completionDateFrom + ", " + completionDateTo + ", " + dutyPerson);
		
		if (null == workStatus) workStatus = "";
		if (null == completionDateFrom) completionDateFrom = "";
		if (null == completionDateTo) completionDateTo = "";
		if (null == dutyPerson) dutyPerson = "";
		
		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}

		List<String> args = new ArrayList<String>();
		String hql = "from CheckWorkOrder cwo where cwo.appointPeople=?";
		args.add(dutyPerson);
		
		if (!"".equals(completionDateFrom) || !"".equals(completionDateTo)) {
			if ("".equals(completionDateFrom)) 
				completionDateFrom = "1900/01/01 00:00:00";
			if ("".equals(completionDateTo)) 
				completionDateTo = "2999/01/01 00:00:00";
			
			hql += " and cwo.exstatusDate>=to_date(?,'YYYY-MM-DD HH24:MI:SS') " +
					" and cwo.exstatusDate<=to_date(?,'YYYY-MM-DD HH24:MI:SS') ";
			
			args.add(completionDateFrom);
			args.add(completionDateTo);
		}
		
		if (!"".equals(workStatus)) {
			hql += " and cwo.status=?";
			args.add(workStatus);
		}
		
		List<CheckWorkOrder> list = this.checkWorkOrderDao.findByHql(hql, args.toArray());
		
		if (list.size() > 0) {
			//更新下载数据的时间
			for (CheckWorkOrder cwo : list) {
				cwo.setDownLoadDt(DateUtil.dateFormat(new Date()));
				cwo.setUpdatePerson(dutyPerson);
				cwo.setUpdateDt(new Date());
				checkWorkOrderDao.saveOrUpdate(cwo);
			}
			return toJsonResult(list);
		}
		else
			return toJsonResult("没有数据");
	}

	@Override
	public boolean updateCheckWorkOrder(String assignmentId,
			String workStatus, String workComment, String completionDate,
			String updatePerson, String beginTime, String endTime) {

		logger.info("request args : " + assignmentId + ", " + workStatus + ", " 
				+ workComment + ", " + completionDate + ", " + updatePerson);
		
		boolean result = false;
		Long aid = 0L;
		try {
			aid = Long.parseLong(assignmentId);
		} catch (Exception ex) {
			logger.error("输入的参数格式错误", ex);
		}
		
		if (aid > 0) {
			CheckWorkOrder cwo = checkWorkOrderDao.get(aid);
			
			Date oDate = cwo.getUpdateDt();
			if (oDate == null) oDate = DateUtil.parseDate("1900-01-01 01:01:01");
			
			if ("1".equals(workStatus)) {
				//状态还是待处理，代表PDA上并未处理该记录，将PDA下载时间置空，下次还可以下载进行处理
				cwo.setDownLoadDt("");
			} else {
				//更新状态、处理时间、备注和PDA上传时间
				cwo.setStatus(workStatus);
				try {
					cwo.setExstatusDate(DateUtil.dateParse(completionDate));
				} catch (Exception ex) {
					logger.warn("更新状态变更时间发生异常", ex);
				}
				cwo.setWorkComment(workComment);
				cwo.setUploadDt(DateUtil.dateFormat(new Date()));
			}
			cwo.setUpdatePerson(updatePerson);
			cwo.setUpdateDt(new Date());
			cwo.setBeginTime(DateUtil.dateParse(beginTime));
			cwo.setEndTime(DateUtil.dateParse(endTime));
			checkWorkOrderDao.saveOrUpdate(cwo);
			
			CheckWorkOrder newObj = checkWorkOrderDao.get(aid);
			
			result = newObj.getUpdateDt().after(oDate);
		}
		return result;
	}

	@Override
	public String listCheckTaskByAssignmentId(String assignmentId) {
		if (null == assignmentId) assignmentId = "";
		
		logger.info("request args : " + assignmentId);

		Long aid = 0L;
		try {
			aid = Long.parseLong(assignmentId);
		} catch (Exception ex) {
			logger.error("输入的参数格式错误", ex);
			return toJsonResult("输入的参数格式错误");
		}
		
		if (aid <= 0) {
			return toJsonResult("必须输入参数");
		}

		String hql = "from CheckTask ct where ct.assignmentId=?";
		
		List<CheckTask> list = this.checkTaskDao.findByHql(hql, new Long[]{ aid });
		
		if (list.size() == 0) return toJsonResult("没有数据");
		
		return toJsonResult(list);
	}

	@Override
	public boolean updateCheckTask(String assignmentId, String taskId,
			String status, String completionDate, String updatePerson) {
		
		logger.info("request args : " + assignmentId + ", " + taskId + ", " 
				+ status + ", " + completionDate + ", " + updatePerson);
		
		boolean result = false;
		Long aid = 0L;
		Long tid = 0L;
		try {
			aid = Long.parseLong(assignmentId);
			tid = Long.parseLong(taskId);
		} catch (Exception ex) {
			logger.error("输入的参数格式错误", ex);
		}
		
		if (aid > 0 && tid > 0) {
			CheckTask checkTask = checkTaskDao.getByUniqueKey(aid, tid);
			
			Date oDate = checkTask.getLastEditDt();
			if (oDate == null) oDate = DateUtil.parseDate("1900-01-01 01:01:01");
			
			if ("1".equals(status)) {
				//状态还是待处理，代表PDA上并未处理该记录，将PDA下载时间置空，下次还可以下载进行处理
				checkTask.setDownLoadDt("");
			} else {
				//更新状态、处理时间、备注和PDA上传时间
				checkTask.setStatus(status);
				try {
					checkTask.setExstatusDate(DateUtil.dateParse(completionDate));
				} catch (Exception ex) {
					logger.warn("更新状态变更时间发生异常", ex);
				}
			}
			checkTask.setLastEditBy(updatePerson);
			checkTask.setLastEditDt(new Date());
			
			checkTaskDao.saveOrUpdate(checkTask);
			
			CheckTask newObj = checkTaskDao.getByUniqueKey(aid, tid);
			
			result = newObj.getLastEditDt().after(oDate);
		}
		return result;
	}

	@Override
	public String listRepairWorkOrder(String dutyPerson) {	
		logger.info("request args : " + dutyPerson);
		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}
		String hql = "from RepairWorkOrder rwo where rwo.appointPeople=? and (rwo.status='1' or rwo.status='5')";
		List<RepairWorkOrder> rwoList = this.repairWorkOrderDao.findByHql(hql, 
				new String[]{dutyPerson});
		
		//List<RepairWorkOrder> rwoList =  repairWorkOrderDao.listRepairWorkOrderByDutyPerson(dutyPerson, null, "1", null, null, null);
		if(null == rwoList || rwoList.size() == 0) return toJsonResult("没有数据");;
		//更新下載數據
		for(RepairWorkOrder rwo : rwoList){
			rwo.setDownLoadDt(DateUtil.dateFormat(new Date()));
			rwo.setLastEditBy(dutyPerson);
			rwo.setLastEditDt(new Date());
			repairWorkOrderDao.save(rwo);
		}
		return toJsonResult(rwoList);
	}
	@Override
	public String queryRepairWorkOrder(String workOrderNo, String workStatus, 
			String assetNo, String completionDateFrom, String completionDateTo,
			String dutyPerson) {
		/*String completionDateFromFormat=DateUtil.(completionDateFrom,"yyyy-MM-dd");
		String completionDateToFormate=DateUtil.dateParse(completionDateTo);*/
		logger.info("request args : " + workOrderNo + ", " + workStatus + ", " 
				+ assetNo + ", " + completionDateFrom + ", " + completionDateTo + 
				", " + dutyPerson);
		List<RepairWorkOrder> rwoList =  repairWorkOrderDao.listRepairWorkOrderByDutyPerson(dutyPerson, workOrderNo, workStatus, assetNo, completionDateFrom, completionDateTo);
		if(null == rwoList || rwoList.size() == 0) return toJsonResult("没有数据");;
		return toJsonResult(rwoList);
	}

	@Override
	public boolean updateRepairWorkOrder(String assignmentId,
			String workStatus, String workComment,
			String updatePerson, String beginTime, String endTime) {
		logger.info("request args : " + assignmentId + ", " + workStatus + ", " 
				+ workComment + ", " + ", " + updatePerson);
  		
		List<RepairWorkOrder> rwoList =  repairWorkOrderDao.listRepairWorkOrderByDutyPerson(updatePerson, assignmentId, null, null, null, null);
		if(null == rwoList || rwoList.size() == 0) return false;
		for(RepairWorkOrder rwo : rwoList){
			Date nowTime = Calendar.getInstance().getTime();
			rwo.setStatus(workStatus);
			rwo.setExstatusDate(nowTime);
			rwo.setBeginTime(DateUtil.dateParse(beginTime));
			rwo.setEndTime(DateUtil.dateParse(endTime));
			rwo.setRemark(workComment);
			rwo.setUploadDt(DateUtil.dateFormat(nowTime));
			repairWorkOrderDao.saveOrUpdate(rwo);
		}
		return true;
		
	}

	@Override
	public String listWatermeterReadingWorkOrder(String dutyPerson) {
		logger.info("request args : " + dutyPerson);
		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}
		Date nowDate = new Date();
		String hql = "from WaterMeterMonthPlanRead wmmpr where wmmpr.executor=? and wmmpr.degree=0"+
					" and wmmpr.planID in (select plan.planId from WaterMeterMonthPlan plan where plan.planStatus='1' and plan.executor=? and plan.beginTime <=sysDate and sysDate < plan.endTime)";
		List<WaterMeterMonthPlanRead> list = 
				this.waterMeterMonthPlanReadDao.findByHql(hql, new String[]{dutyPerson,dutyPerson});
		if (list.size() > 0) {
			//更新下载数据的时间
			for (WaterMeterMonthPlanRead wmmpr : list) {
				wmmpr.setDownloadTime(DateUtil.dateFormat(new Date()));
				wmmpr.setLastEditBy(dutyPerson);
				wmmpr.setLastEditDt(new Date());
				waterMeterMonthPlanReadDao.saveOrUpdate(wmmpr);
			}
			//((WaterMeterMonthPlanRead)list.get(0)).getBarCode()
			 //toJsonResult(list)
			 return  toJsonResult(list)   ;
		}
		else
			return toJsonResult("没有数据");
		
	}
	@Override
	public String listWaterMeterPlan(String dutyPerson){
		logger.info("request args : " + dutyPerson);
		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}
		String hql = "from WaterMeterMonthPlan where executor=? and  planStatus =1L and beginTime<=sysDate and sysDate< endTime)";
		List<WaterMeterMonthPlan> list = this.waterMeterMonthPlanDao.findByHql(hql,new String[]{dutyPerson});
		if(list.size() >0) return toJsonResult(list);
		else return toJsonResult("没有数据");
		
	}
	@Override
	public String queryWatermeterReadingWorkOrder(String meterNo, String houseId, 
			String completionDateFrom, String completionDateTo,
			String dutyPerson) {
		
		logger.info("request args : " + meterNo + ", " + houseId + ", "
				+ completionDateFrom + ", " + completionDateTo + ", " + dutyPerson);

		if (null == meterNo) meterNo = "";
		if (null == houseId) houseId = "";
		if (null == completionDateFrom) completionDateFrom = "";
		if (null == completionDateTo) completionDateTo = "";
		if (null == dutyPerson) dutyPerson = "";
		
		if ("".equals(dutyPerson)) {
			return toJsonResult("亲，你要查谁的资料？");
		}
		
		QueryFilter filter = new QueryFilter(0, 200);
		filter.addFilter("Q_amId_S_LK", meterNo);
		filter.addFilter("Q_pdaWaterMeter.aparmentId_S_LK", houseId);
		filter.addFilter("Q_recordTime_D_GE", completionDateFrom);
		filter.addFilter("Q_recordTime_D_LE", completionDateTo);
		List<PdaWaterList> list = this.pdaWaterListDao.getAll(filter);
		
		if (list.size() > 0){
			return toJsonResult(list);
			}
		else
			return toJsonResult("没有数据");
		
		
	}

	@Override
	public boolean updateWatermeterReadingWorkOrder(String mprId,
			String meterDegree, String completionDate, String updatePerson) {
		
		logger.info("request args : " + mprId + ", " + meterDegree + ", " 
				+ completionDate + ", " + updatePerson);
		
		boolean result = false;
		Long id = 0L;
		Long degree = 0L;
		try {
			id = Long.parseLong(mprId);
			degree = Long.parseLong(meterDegree);
		} catch (Exception ex) {
			logger.error("输入的参数格式错误", ex);
		}
		
		if (id > 0 && degree >= 0) {
			WaterMeterMonthPlanRead wmmpr = waterMeterMonthPlanReadDao.get(id);
			
			Date oDate = wmmpr.getLastEditDt();
			if (oDate == null) oDate = DateUtil.parseDate("1900-01-01 01:01:01");
			
			//更新状态、处理时间、备注和PDA上传时间
			wmmpr.setDegree(degree);
			wmmpr.setReadingTime(DateUtil.dateParse(completionDate));
			
			wmmpr.setUploadTime(DateUtil.dateFormat(new Date()));
		
			wmmpr.setLastEditBy(updatePerson);
			wmmpr.setLastEditDt(new Date());
		
			waterMeterMonthPlanReadDao.saveOrUpdate(wmmpr);
			
			WaterMeterMonthPlanRead newObj = waterMeterMonthPlanReadDao.get(id);
			
			result = newObj.getLastEditDt().after(oDate);
		}
		return result;
	}

	@Override
	public String listAmmeterReadingWorkOrder(String dutyPerson) {

		logger.info("request args : " + dutyPerson);

		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}
		
		String hql = "from AmMonthPlanRead ammpr where ammpr.executor=? and ammpr.degree=0 "+
					" and ammpr.planID in ( " +
					"    select planId from AmMonthPlan plan " +
					"    where plan.planStatus='1' and plan.executor=? " +
					"    and plan.beginTime <=sysDate " +
					"    and sysDate < plan.endTime " +
					" )";
		List<AmMonthPlanRead> list = this.amMonthPlanReadDao.findByHql(hql, 
				new String[]{dutyPerson,dutyPerson});
		
		if (list.size() > 0) {
			//更新下载数据的时间
			for (AmMonthPlanRead ammpr : list) {
				ammpr.setDownloadTime(DateUtil.dateFormat(new Date()));
				ammpr.setLastEditBy(dutyPerson);
				ammpr.setLastEditDt(new Date());
				amMonthPlanReadDao.saveOrUpdate(ammpr);
			}
			
			return toJsonResult(list);
		}
		else
			return toJsonResult("没有数据");
		
	}
	@Override
	public String listAmMeterMonthPlan(String dutyPerson){
		logger.info("request args : " + dutyPerson);
		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}
		String hql = "from AmMonthPlan where executor=? and  planStatus =1L and beginTime<=sysDate and sysDate< endTime)";
		List<AmMonthPlan> list = this.amMonthPlanDao.findByHql(hql,new String[]{dutyPerson});
		if(list.size() >0) return toJsonResult(list);
		else return toJsonResult("没有数据");
		
	}
	@Override
	public String queryAmmeterReadingWorkOrder(String meterNo,String houseId,
			String completionDateFrom, String completionDateTo,
			String dutyPerson
			) {
		logger.info("request args : " + meterNo + ", " + completionDateFrom + ", " 
				+ completionDateTo + ", " + dutyPerson);
		
		if (null == meterNo) meterNo = "";
		if (null == completionDateFrom) completionDateFrom = "";
		if (null == completionDateTo) completionDateTo = "";
		if (null == dutyPerson) dutyPerson = "";
		
		if ("".equals(dutyPerson)) {
			return toJsonResult("要谁的资料？");
		}

		QueryFilter filter = new QueryFilter(0, 200);
		filter.addFilter("Q_amId_S_LK", meterNo);
		filter.addFilter("Q_pdaAmMeter.aparmentId_S_LK", houseId);
		filter.addFilter("Q_recordtime_D_GE", completionDateFrom);
		filter.addFilter("Q_recordtime_D_LE", completionDateTo);
		List<PdaAmMeterList> list = this.pdaAmMeterListDao.getAll(filter);
		
		if (list.size() > 0){
			return toJsonResult(list);
			}
		else
			return toJsonResult("没有数据");
	

	}

	@Override
	public boolean updateAmmeterReadingWorkOrder(String mprId,
			String meterDegree, String completionDate, String updatePerson) {
		
		logger.info("request args : " + mprId + ", " + meterDegree + ", " 
				+ completionDate + ", " + updatePerson);
		
		boolean result = false;
		Long id = 0L;
		Long degree = 0L;
		try {
			id = Long.parseLong(mprId);
			degree = Long.parseLong(meterDegree);
		} catch (Exception ex) {
			logger.error("输入的参数格式错误", ex);
		}
		
		if (id > 0 && degree >=0) {
			
			AmMonthPlanRead ammpr = amMonthPlanReadDao.get(id);
			
			Date oDate = ammpr.getLastEditDt();
			if (oDate == null) oDate = DateUtil.parseDate("1900-01-01 01:01:01");
			
			//更新状态、处理时间、备注和PDA上传时间
			ammpr.setDegree(degree);
			ammpr.setReadingTime(DateUtil.dateParse(completionDate));
			
			ammpr.setUploadTime(DateUtil.dateFormat(new Date()));
		
			ammpr.setLastEditBy(updatePerson);
			ammpr.setLastEditDt(new Date());
		
			amMonthPlanReadDao.saveOrUpdate(ammpr);
			
			AmMonthPlanRead newObj = amMonthPlanReadDao.get(id);
			
			result = newObj.getLastEditDt().after(oDate);
		}
		return result;
	}
	

	private String toJsonResult(String msg) {
		return "{\"message\":\"" + msg + "\",\"data\":[]}";
	}
	private String toJsonResult(@SuppressWarnings("rawtypes") List list) {
		//转成json格式后返回
		Gson gson = new GsonBuilder()
				.excludeFieldsWithoutExposeAnnotation()
				.serializeNulls()
				.setDateFormat("yyyy/MM/dd HH:mm:ss")
				.create();
		
		return "{\"message\":\"\",\"data\":" + gson.toJson(list) + "}";
	}

	/**
	 * 根据用户账号返回用户角色
	 */
	@Override
    public String listUserRoles(String userName) {
		
		logger.info("request args : " + userName);
		
		if(null!=userName && "" != userName)
		{
			AppUser listAppUser = appUserDao.findByUserName(userName);
			Set<AppRole> roles = listAppUser.getRoles();
			logger.info("user have roles size : " + roles.size());
			//将获取的RoleCode组成字符串，已逗号隔开
			String roleCodeStr = "";
			for (AppRole role : roles) {
				roleCodeStr = roleCodeStr=="" ? role.getRoleCode() : roleCodeStr+","+role.getRoleCode();
			}
			return roleCodeStr;
		}
		return null;
	}
	public String listAttachment(String barCode){
		if(null == barCode) return toJsonResult("条形码为空");
		PdaMdAssetInfo pdaMdAssetInfo = pdaMdAssetInfoDao.getByBarCode(barCode);
		if(null==pdaMdAssetInfo) return toJsonResult("没有资产信息");
		String assetNo = pdaMdAssetInfo.getAssetNo();
		String siteId = pdaMdAssetInfo.getSiteId();
		List<PdaMdAssetDetail>pdaMdAssetDetail = pdaMdAssetDetailDao.getByAssetNoAndSiteId(assetNo, siteId);
		if (pdaMdAssetDetail.size() > 0) return toJsonResult(pdaMdAssetDetail);
		else
			return toJsonResult("没有数据");
	}

	@Override
	public boolean insertMaterial(String assignmentId ,String woNum, String barCode, String account,String detail) {
		boolean result=false;
		boolean qty = true;
		String materialDetail[] = detail.split(";");
		//验证物料数量类型是否正确
		for(int i = 0 ; i < materialDetail.length;i++){
			String materialElement[] =materialDetail[i].split(",");
			try{
				double itemqty = Double.valueOf(materialElement[1]);
			}
			catch(Exception e){
				logger.info(e.getMessage());
				qty = false;
				break;
			}
		}
		//物料数量类型正确，同步EAM
		if(qty){
			for(int i = 0 ; i < materialDetail.length;i++){
				String materialElement[] =materialDetail[i].split(",");
				double itemqty = Double.valueOf(materialElement[1]);
				try{
					result = eamService.createMR(account, woNum, materialElement[0], itemqty, "", "");
				}
				catch(Exception e){
					logger.info(e.getMessage());
				}
			}
		}
		if(result){
			PdaMaterialHead pdaMaterialHead = new PdaMaterialHead();
			pdaMaterialHead.setBarCode(barCode);
			pdaMaterialHead.setWoNum(woNum);
			pdaMaterialHead.setCreatedBy(account);
			pdaMaterialHead.setCreatedDt(new Date());
			pdaMaterialHead.setLastEditedDt(new Date());
			pdaMaterialHead.setLastEditedBy(account);
			pdaMaterialHead.setLastEditedBy(account);
			pdaMaterialHead.setStatus("4");
			pdaMaterialHead.setIsSynchro("0");
			try{
				long headId = pdaMaterialHeadDao.save(pdaMaterialHead);
				//String materialDetail[] = detail.split(";");
				for(int i = 0 ; i < materialDetail.length;i++){
					String materialElement[] =materialDetail[i].split(",");
					PdaMaterialDetail pdaMaterialDetail = new PdaMaterialDetail();
					pdaMaterialDetail.setItemNum(materialElement[0]);
					pdaMaterialDetail.setQuantity(materialElement[1]);
					pdaMaterialDetail.setCreatedBy(account);
					pdaMaterialDetail.setCreatedDt(new Date());
					pdaMaterialDetail.setHeadId(headId);
					pdaMaterialDetailDao.save(pdaMaterialDetail);
				}
				RepairWorkOrder repairWorkOrder = repairWorkOrderDao.get(Long.parseLong(assignmentId));
				repairWorkOrder.setStatus("4");
				repairWorkOrder.setLastEditBy(account);
				repairWorkOrder.setLastEditDt(new Date());
				repairWorkOrderDao.save(repairWorkOrder);
		
				result = true;
			}
			catch(Exception ex)
			{
				return result;
			}
		}
		
		
		return result;
	}
		@Override
	public boolean insertApplyRepair(String barCode, String recordeId,String applyTime, 
			String remark, String reason,String lacotedId,String workStatus,String estdur) {
		logger.info("insertApplyRepair request args :"+barCode+","+recordeId+","+applyTime+","+remark+","+reason+","+","+lacotedId+","+workStatus+","+estdur);
		boolean result=false;
		if(null ==barCode || barCode=="") return result;
		if(null ==recordeId || recordeId=="") return result;
		if(null ==applyTime || applyTime=="") return result;
		if(null ==workStatus || workStatus=="") return result;
		PdaApplyRepair pdaApplyRepair =new PdaApplyRepair();
		pdaApplyRepair.setBarCode(barCode);
		pdaApplyRepair.setRecordeId(recordeId);
		pdaApplyRepair.setApplyTime(applyTime);
		pdaApplyRepair.setRemark(remark);
		pdaApplyRepair.setReason(reason);
		pdaApplyRepair.setIsSynchro("0");
		pdaApplyRepair.setCreatedDt(new Date());
		pdaApplyRepair.setCreatedBy(recordeId);
		pdaApplyRepair.setLastEditDt(new Date());
		pdaApplyRepair.setLastEditBy(recordeId);
		pdaApplyRepair.setLocatedId(lacotedId);
		pdaApplyRepair.setWorkStatus(workStatus);
		pdaApplyRepair.setEstdur(estdur);
		try{
			pdaApplyRepairDao.save(pdaApplyRepair);
		}
		catch(Exception ex)
		{
			logger.error("申请保修失败",ex);
			return result;
		}
		result=true;
		return result;
	}
		
}

	
